//
//  TFFileUploadManager.m
//  UploadFileTest
//
//  Created by shiwei on 16/2/21.
//  Copyright © 2016年 shiwei. All rights reserved.
//

#import "TFFileUploadManager.h"
#import <MobileCoreServices/UTType.h>
#import <CommonCrypto/CommonDigest.h>

@implementation TFFileUploadManager{
    NSMutableURLRequest *request;
    NSOperationQueue *queue;
    NSURLConnection *_connection;
    NSMutableData *_reveivedData;
}

+(instancetype)shareInstance{
    static TFFileUploadManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[TFFileUploadManager alloc]init];
    });
    
    return manager;
}

-(void)uploadFileWithURL:(NSString *)urlString params:(NSDictionary *)params fileKey:(NSString *)fileKey filePath:(NSString *)filePath completeHander:(void (^)(NSURLResponse *, NSData *, NSError *))completeHander{
    
    NSURL *URL = [[NSURL alloc]initWithString:urlString];
    request = [[NSMutableURLRequest alloc]initWithURL:URL cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30];
    NSString *boundary = @"wfWiEWrgEFA9A78512weF7106A";
    
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    request.HTTPMethod = @"POST";
    request.allHTTPHeaderFields = @{
                                    @"Content-Type":[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]
                                    };
    
    //multipart/form-data格式按照构建上传数据
    NSMutableData *postData = [[NSMutableData alloc]init];
    for (NSString *key in params) {
        NSString *pair = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n",boundary,key];
        [postData appendData:[pair dataUsingEncoding:NSUTF8StringEncoding]];
        
        id value = [params objectForKey:key];
        if ([value isKindOfClass:[NSString class]]) {
            [postData appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
        }else if ([value isKindOfClass:[NSData class]]){
            [postData appendData:value];
        }
        [postData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    //文件部分
    NSString *filename = [filePath lastPathComponent];
    NSString *contentType = AFContentTypeForPathExtension([filePath pathExtension]);
    
    NSString *filePair = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\";Content-Type=%@\r\n\r\n",boundary,fileKey,filename,contentType];
    [postData appendData:[filePair dataUsingEncoding:NSUTF8StringEncoding]];
    
    //[postData appendData:[@"测试文件数据" dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:fileData]; //加入文件的数据
    
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        request.HTTPBody = postData;
    [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)postData.length] forHTTPHeaderField:@"Content-Length"];
    
    _connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [_connection start];
}

#pragma mark - connection delegate

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"reveive Response:\n%@",response);
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (!_reveivedData) {
        _reveivedData = [[NSMutableData alloc]init];
    }
    
    [_reveivedData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"received Data:\n%@",[[NSString alloc] initWithData:_reveivedData encoding:NSUTF8StringEncoding]);
    NSString * replaceStr = [self replaceBack:[[NSString alloc] initWithData:_reveivedData encoding:NSUTF8StringEncoding]];
    NSString * encodeStr = [self dencode:replaceStr];
    NSString * md5Str = [self md5:encodeStr];
    NSLog(@"md5Str:%@", md5Str);
}








//反替换
- (NSString *)replaceBack:(NSString *)getJsonStr{
    NSArray * needToBeReplaceArr = [NSArray arrayWithObjects:@"!", @"@", @"#", @"*", @"^", @"%", @"&", @"(", @")", nil];
    NSArray * replaceArr = [NSArray arrayWithObjects:@"+", @"/", @"=", @"d", @"D", @"b", @"B", @"W", @"w", nil];
    
    NSMutableString * tempString = (NSMutableString *)getJsonStr;
    for (int y = 0; y<needToBeReplaceArr.count; y++) {
        //取出需要替换的字符进行判断
        NSString * arrTempStr = needToBeReplaceArr[y];
        //遍历需要进行替换字符串
        for (int i = 0; i<[getJsonStr length]; i++) {
            char tempChar = [tempString characterAtIndex:i];
            NSString * matchingStr = [NSString stringWithFormat:@"%c", tempChar];
            if ([matchingStr isEqualToString:arrTempStr]) {
                NSRange range = {i, 1};
                tempString = [tempString stringByReplacingCharactersInRange:range withString:replaceArr[y]];
            }
        }
    }
    return tempString;
}

//base64解码
- (NSString *)dencode:(NSString *)base64String
{
    //NSData *base64data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}

//比照时排序
- (NSString *)compareSortKeyDictionary:(NSDictionary *)dict{
    NSMutableString * ns = nil;//数组一个元素
    NSMutableArray * totalValueArr = [NSMutableArray array];//装value的数组的value集合
    //    NSMutableString * totalValueStr = nil;//装value的数组的json字符串
    NSMutableArray * tempTotalValueArr = [NSMutableArray array];;//临时
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    //    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    //    NSLog(@"valueArray:%@",valueArray);
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        if ([valueArray[i] isKindOfClass:[NSArray class]]) {
            
            if ([valueArray[i] count]>0) {
                for (int y = 0; y<[valueArray[i] count]; y++) {
                    //将所有的key放进数组
                    NSArray *insideAllKeyArray = [valueArray[i][y] allKeys];
                    //序列化器对数组进行排序的block 返回值为排序后的数组
                    NSArray *insideAfterSortKeyArray = [insideAllKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
                        NSComparisonResult resuest = [obj1 compare:obj2];
                        return resuest;
                    }];
                    //                    NSLog(@"insideAfterSortKeyArray:%@",insideAfterSortKeyArray);
                    //通过排列的key值获取value
                    NSMutableArray *insidevalueArray = [NSMutableArray array];
                    NSString *insideValueString = nil;
                    for (NSString *insideSortsing in insideAfterSortKeyArray) {
                        if ([insideSortsing isEqualToString:@""] || insideSortsing.length == 0) {
                            insideValueString = @"";
                            [insidevalueArray addObject:insideValueString];
                        }else{
                            insideValueString = [valueArray[i][y] objectForKey:insideSortsing];
                            [insidevalueArray addObject:insideValueString];
                        }
                    }
                    //                    NSLog(@"insidevalueArray:%@",insidevalueArray);
                    NSMutableArray *insideArray = [NSMutableArray array];
                    //body的value里面的一个数组
                    for (int t = 0 ; t < insideAfterSortKeyArray.count; t++) {
                        NSString *insideArraykeyValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",insideAfterSortKeyArray[t],insidevalueArray[t]];
                        [insideArray addObject:insideArraykeyValue];
                    }
                    ns = [insideArray componentsJoinedByString:@","];
                    [totalValueArr addObject:ns];
                }
                if (totalValueArr.count>0) {
                    //                        ns = [totalValueArr componentsJoinedByString:@","];
                    for (int a = 0; a<totalValueArr.count; a++) {
                        //                            // 插入字符串
                        //                            [str insertString:@"abc" atIndex:2];
                        NSMutableString * string = totalValueArr[a];
                        [string insertString:@"{" atIndex:0];
                        [string insertString:@"}" atIndex:string.length];
                        [tempTotalValueArr addObject:string];
                    }
                    ns = [tempTotalValueArr componentsJoinedByString:@","];
                    //插入
                    [ns insertString:@"[" atIndex:0];
                    [ns insertString:@"]" atIndex:ns.length];
                    [valueArray replaceObjectAtIndex:i withObject:ns];
                }else{
                    //插入
                    [ns insertString:@"[{" atIndex:0];
                    [ns insertString:@"}]" atIndex:ns.length];
                    [valueArray replaceObjectAtIndex:i withObject:ns];
                }
                
                
            }else{
                //在这判断数组是否为空
                NSLog(@"走这里");
                NSMutableString *ns = [NSMutableString stringWithFormat:@""];
                //插入
                [ns insertString:@"[" atIndex:0];
                [ns insertString:@"]" atIndex:ns.length];
                [valueArray replaceObjectAtIndex:i withObject:ns];
            }
        }
        NSString *finalValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:finalValue];
    }
    NSMutableString * sstr = [signArray componentsJoinedByString:@","];
    //插入
    [sstr insertString:@"{" atIndex:0];
    [sstr insertString:@"}" atIndex:sstr.length];
    
    //判断字符串中是否包含"[{，如果有，替换为[{
    if([sstr rangeOfString:@"\"[{"].location != NSNotFound) {
        NSRange range2 = [sstr rangeOfString:@"\"[{"];
        [sstr replaceCharactersInRange:range2 withString:@"[{"]; //不是range2.location
        NSRange range3 = [sstr rangeOfString:@"}]\""];
        [sstr replaceCharactersInRange:range3 withString:@"}]"];
    }
    return sstr;
    
}

//MD5加密
- (NSString *)md5:(NSString *)str {
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    return digest;
}














-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"fail connect:\n%@",error);
}


static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
#ifdef __UTTYPE__
    NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
    NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
    if (!contentType) {
        return @"application/octet-stream";
    } else {
        return contentType;
    }
#else
#pragma unused (extension)
    return @"application/octet-stream";
#endif
}

@end
